package com.wjs.controller;

import com.wjs.entity.Brand;
import com.wjs.entity.Phone;
import com.wjs.service.BrandService;
import com.wjs.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @Autowired
    private PhoneService phoneService;

    @RequestMapping("/selectAll")
    public String selectAll(Model model){
        List<Brand> brands = brandService.selectAll();
        model.addAttribute("brands",brands);
        return "/brand-list.jsp";
    }

    @RequestMapping("/beforeInsert")
    public String beforeInsertPhone(Model model){
        List<Brand> brands = brandService.selectAll();
        model.addAttribute("brands",brands);
        return "/addphone.jsp";
    }

    @RequestMapping("/insertBrand")
    public String insertBrand(Brand brand){
        brandService.insertBrand(brand);
        return "redirect:/brand/selectAll.do";
    }

    @RequestMapping("/deleteBrand")
    public String deleteBrand(Integer id){
        Brand brand=brandService.selectById(id);
        if (brand.getPhones().size()==0){
            brandService.deleteBrandById(id);
        }else {
            for (Phone phone : brand.getPhones()) {
                phoneService.deletePhoneById(phone.getId());
            }
            brandService.deleteBrandById(id);
        }
        return "redirect:/brand/selectAll.do";
    }
}
